package com.tianqi.familymap.presenter

import android.content.Context
import android.content.Intent
import com.tianqi.familymap.base.BasePresenter
import com.tianqi.familymap.http.DataManager
import com.tianqi.familymap.model.PageBean
import com.tianqi.familymap.model.RecommendMultipleModel
import com.tianqi.familymap.model.TQBean
import com.tianqi.familymap.ui.inter.IBaseView
import com.tianqi.familymap.ui.view.IRecommentView
import com.tianqi.familymap.utils.ContantUtils
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

class RecommentPresenter(private val context: Context) : BasePresenter {
    private var manager:DataManager? = null
    private var compositeDisposable:CompositeDisposable? = null
    private var mIRecommentView:IRecommentView? = null
    private var bean:TQBean<PageBean<RecommendMultipleModel>>? = null

    override fun onCreate() {
        manager = DataManager(context)
        compositeDisposable = ContantUtils.compositeDisposable
    }

    override fun onDestory() {
        if (!compositeDisposable!!.isDisposed) {
            compositeDisposable!!.dispose(); //解除订阅
        }
    }

    override fun onStart() {
    }

    override fun pause() {
    }

    override fun attachView(view: IBaseView) {
        mIRecommentView = view as IRecommentView
    }

    override fun attachIncomingIntent(intent: Intent) {
    }

    fun getRecomment(token:String,page:Int){
        val recommend = manager!!.getRecomment(token,page)
        recommend!!.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<TQBean<PageBean<RecommendMultipleModel>>?>{
                override fun onSubscribe(d: Disposable) {
                    compositeDisposable!!.add(d);
                }

                override fun onNext(t: TQBean<PageBean<RecommendMultipleModel>>) {
                    bean = t
                }

                override fun onError(e: Throwable) {
                    mIRecommentView?.showErrorMsg("请求失败:\n$e")
                }

                override fun onComplete() {
                    mIRecommentView?.showAndroidData(bean!!)
                }

            })
    }
}